<?php

namespace app\admin\controller\categorys;

use app\common\controller\Backend;
use fast\Tree;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Index extends Backend
{

    /**
     * Index模型对象
     * @var \app\admin\model\categorys\Index
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\categorys\Index;


        //获取数据并转成数组
        $list = collection($this->model->select())->toArray();
        //将数据给到这个方法中
        Tree::instance()->init($list);
        //这创建了一个空数组，然后使用 getTreeList() 方法从 Tree 实例中检索一组树节点
        //将根节点 ID (0) 作为参数传递给它的 getTreeArray() 方法。
        $groupdata = [];
        $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
        //遍历 $result 数组，将每个树节点的 name 字段作为 $groupdata 数组中一个条目的值，将 id 字段作为键。
        foreach ($result as $k => $v) {
            $groupdata[$v['id']] = $v['name'];
        }
        //返回
        $this->view->assign("statusList", $groupdata);

    }



    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        //判断请求为Ajax
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            //查询数据库获得结果
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            //遍历对数据的可见性设置
            foreach ($list as $row) {
                $row->visible(['id','name','createtime','status','level','user_id']);

            }
            //初始化并传入结果
            Tree::instance()->init($list);
            $groupdata = [];
            //获取树形结构列表
            $result1 = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            foreach ($result1 as &$key){
                $key['level']=getleveltit($key['level']);
            }
            //返回值
            $result = array("total"=>$list->total(),"rows"=>$result1);
            //返回
            return json($result);
        }
        return $this->view->fetch();
    }


    //上传文件
    public function addfile(){

        if ($this->request->isPost()) {

            $file=  $this->request->post("file");
            $group_id = $this->request->post("ids");
            $this->daoru($file,$group_id);
            die;
        }

        $ids=$this->request->param('ids');

        $info=Db::name('categorys')->where(['id'=>$ids])->find();

        //上一个

        $p3=Db::name('categorys')->where(['id'=>$info['pid']])->find();
        $p2=Db::name('categorys')->where(['id'=>$p3['pid']])->find();
        $p1=Db::name('categorys')->where(['id'=>$p2['pid']])->find();
        $p0=Db::name('categorys')->where(['id'=>$p1['pid']])->find();

        $this->assign("p0", $p0);
        $this->assign("info", $info);
        return $this->view->fetch();


    }


    /**
    写入到数据库
     */
    public function daoru($file,$types_id){
        $filePath = ROOT_PATH  . 'public'  . $file;

        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, 'w');
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding !== 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }


        //加载文件
        $insert = [];

        $reader->setReadDataOnly(true);
        if (!$PHPExcel = $reader->load($filePath)) {
            $this->error(__('Unknown data format'));
        }
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
        $fields = [];

        for ($currentRow = 1; $currentRow <= $allRow; $currentRow++) {
            $values = [];
            for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $values[] = is_null($val) ? '' : $val;
            }
            $row = [];


            $salt=rand(1000000,9999999);

            $user['group_id']=$types_id;
            $user['username']=$values[0];
            $user['email']=$values[0].'@qq.com';
            $user['nickname']=$values[1];
            $user['bio']=$values[2];
            $user['salt']=$salt;
            $user['password']=md5(md5($values[0]) . $salt);
            $user['level']=0;
            $user['money']=0;
            $user['status']='normal';
            $user['loginip']='127.0.0.1';

            $find=Db::name('user')->where(['username'=>$user['username']])->find();
            if (!$find){
                Db::name('user')->data($user)->insert();
            }

        }

        $this->success();



    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


}
